﻿using CodeCarvings.Piczard;
using LuShanTea.Admin.Web.App_Start;
using LuShanTea.Admin.Web.Models;
using LuShanTea.Common;
using LuShanTea.DTO;
using LuShanTea.IService;
using LuShanTea.Web.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LuShanTea.Admin.Web.Controllers
{
    public class UserController : Controller
    {
        public IUserService UserService { get; set; }


        [CheckPermission("User.List")]
        // GET: User
        public ActionResult List()
        {
            ViewBag.TotalCount = UserService.GetTotalCount();
            return View();
        }

        [CheckPermission("User.List")]
        [HttpPost]
        public ActionResult List(int currentPage)
        {
            var users = UserService.GetPageData(10, currentPage);

            return Json(new AjaxResult { Status = "ok", Data = users });
        }

        [CheckPermission("User.Add")]
        public ActionResult AddNew()
        {
            return View();
        }

        [CheckPermission("User.Add")]
        [HttpPost]
        public ActionResult AddNew(UserAddNewModel model)
        {
            if (!ModelState.IsValid)
            {
                string[] errors = MVCHelper.GetValidMsg(ModelState).Split('\r');
               
                return Json(new AjaxResult { Status = "error", ErrorMsg = errors[0] });
            }


            var user = UserService.GetByPhoneNum(model.PhoneNumber);

            if (user != null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "手机号已存在" });
            }

            user = UserService.GetByEmail(model.Email);

            if (user != null)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "邮箱已存在" });
            }


            UserAddNewDTO userAdd = new UserAddNewDTO();
            userAdd.Email = model.Email;
            userAdd.PhoneNum = model.PhoneNumber;
            userAdd.Gender = model.Gender == 1 ? true : false;
            userAdd.Name = model.Name;
            userAdd.NickName = model.NiceName;
            userAdd.Pwd = model.Password;
            userAdd.ImgSrc = model.ImgSrc;

            UserService.AddNew(userAdd);

            return Json(new AjaxResult { Status = "ok" });
        }

        [CheckPermission("User.Edit")]
        public ActionResult Edit(long id)
        {
            var user = UserService.GetById(id);

            if (user == null)
            {
                return Content("未找到ID为" + id + "的用户");
            }

            return View(user);
        }

        [CheckPermission("User.Edit")]
        [HttpPost]
        public ActionResult Edit(UserEditModel model)
        {
            if (!ModelState.IsValid)
            {
                string[] errors = MVCHelper.GetValidMsg(ModelState).Split('\r');
                return Json(new AjaxResult { Status = "error", ErrorMsg = errors[0] });
            }

            var user = UserService.GetById(model.UserId);

            if (user == null)
            {
                return Content("未找到ID为" + model.UserId + "的用户");
            }

            var dataUser = UserService.GetByPhoneNum(model.PhoneNumber);
            if (dataUser != null && dataUser.Id != model.UserId)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "手机号已存在" });
            }

            dataUser = UserService.GetByEmail(model.Email); ;
            if (dataUser != null && dataUser.Id != model.UserId)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "邮箱已存在" });
            }

            UserUpdateDTO userUpate = new UserUpdateDTO();
            userUpate.Id = model.UserId;
            userUpate.Email = model.Email;
            userUpate.PhoneNum = model.PhoneNumber;
            userUpate.Gender = model.Gender == 1 ? true : false;
            userUpate.Name = model.Name;
            userUpate.NickName = model.Name;
            userUpate.ImgSrc = model.ImgSrc ?? user.ImgSrc;

            UserService.Update(userUpate);

            return Json(new AjaxResult { Status = "ok" });
        }

        [CheckPermission("User.Upload")]
        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            if (file.ContentLength <= 0 || file.ContentLength >= 1024 * 1024 * 2)
            {
                return Json(new AjaxResult { Status = "error", ErrorMsg = "文件过大或过小" });
            }

            string md5 = CommonHelper.CalcMD5(file.InputStream);
            string ext = Path.GetExtension(file.FileName);

            string[] exts = { ".jpg", ".png", "gif", ".jpeg", ".bmp" };

            if (!exts.Contains(ext))
            {
                return Json(new AjaxResult
                {
                    Status = "error",
                    ErrorMsg = "请勿上传非图片文件,支持格式( .jpg, .png, gif, .jpeg, .bmp)"
                });
            }

            string path = "upload/userImg/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + md5 + ext;

            //缩略图地址 150*150
            //string thumbPath = path + @"?imageView2/2/w/200/h/200/interlace/1/q/100" ;


            //string fullPath = HttpContext.Server.MapPath("~" + path);
            //string thumbFullPath = HttpContext.Server.MapPath("~" + thumbPath);


            //指针归零
            file.InputStream.Position = 0;

            UploadFile uploadFile = new UploadFile();

            AjaxResult ajaxResult = uploadFile.UploadImg(path, file.InputStream);

            #region 本地存储
            //创建目录
            //new FileInfo(fullPath).Directory.Create();
            ////指针归零
            //file.InputStream.Position = 0;

            ////缩略图
            //ImageProcessingJob jobThumb = new ImageProcessingJob();
            //jobThumb.Filters.Add(new FixedResizeConstraint(150, 150));//缩略图尺寸 200*200 
            //jobThumb.SaveProcessedImageToFileSystem(file.InputStream, thumbFullPath);

            //file.InputStream.Position = 0;
            //file.SaveAs(fullPath);
            #endregion

            return Json(new AjaxResult { Status = "ok", Data = path });
        }

        [CheckPermission("User.Delete")]
        [HttpPost]
        public ActionResult Delete(long userId)
        {
            UserService.MarkDeleted(userId);

            return Json(new AjaxResult { Status = "ok" });
        }


        [CheckPermission("User.Delete")]
        [HttpPost]
        public ActionResult BatchDel(long[] userIds)
        {
            foreach (var userId in userIds)
            {
                UserService.MarkDeleted(userId);
            }

            return Json(new AjaxResult { Status = "ok" });
        }
    }
}